import axios from "axios";
import {baseUrl} from "@/setting.js";
import Qilin from "qilin-utils";
import router from "@/router/index.js";
import {loading} from "@/global/utils/loading.js";

const service=axios.create({
    baseURL:baseUrl,
    timeout:10*1000
});

//请求拦截
service.interceptors.request.use((requestConfig)=>{
    // console.log(requestConfig); //请求配置项
    loading.show();
    if(Qilin.Storage.getValueLocalStorage("qilinToken")){
        requestConfig.headers.Authorization=Qilin.Storage.getValueLocalStorage("qilinToken");
    };
    return requestConfig;
},(error)=>{
    return Promise.reject(error);
});

//响应拦截
service.interceptors.response.use((response)=>{
    loading.hide();
    return response.data;
},(error)=>{
    loading.hide();
    if(error.response.status === 401){//此时属于token失效
        ElMessage.error({
            message:"token失效，请重新登录!",
            center:true
        });
        localStorage.removeItem("qilinToken"); //清除token
        router.replace("/login");
    }else{
        if(!!error.response.data.message){
            ElMessage.error({ //错误提醒
                message:error.response.data.message,
                center:true
            });
        }else{
            ElMessage.error({
                message:"系统错误",
                center:true
            });
        };
    };
    return Promise.reject(error);
});

export default service;
